<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>

    </title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color: red;
            position: fixed;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
  var box=document.querySelector(".box")
  box.addEventListener('mousedown', function(e){
        var x =e.pageX - box.offsetLeft;
        var y = e.pageY - box.offsetTop;

        function fun(e){
            var left = e.pageX - x;
            var top = e.pageY - y;

            box.style.left=left+"px "
            box.style.top = top + 'px';
        }
        
        document.addEventListener('mousemove', fun)

        document.addEventListener('mouseup', function(){
            document.removeEventListener('mousemove', fun);
        });
    });
</script>
</html>